<!-- 客服 -->
<template>
	<view class="chat-wrap">
		<scroll-view @click="closeAll" class="scroll-box" scroll-y="true" :scroll-with-animation="false" :enable-back-to-top="true" :show-scrollbar="false" :scroll-into-view="scrollInto">
			<u-loadmore style="margin-top: 60rpx;" v-if="chatMsgList.length && logStatus == 'loadmore'" :status="logStatus" :loadText="loadText" icon-type="circle" @loadmore="logLoadmore" />
			<!-- 聊天列表 -->
			<view class="cu-chat">
				<block v-for="(chat, index) in chatMsgList" :key="index">
					<view v-if="chat">
						<view class="time-box">
							<view class="cu-info" v-if="showTime(chat.date, index) || index===chatMsgList.length-1">
								{{formatDate(chat.date)}}
							</view>
						</view>

						<!-- 自己  -->
						<view class="cu-item" :class="{ self: chat && chat.identify === 'user' }">
							<!-- 对方头像 -->
							<view v-if="chat && chat.identify !== 'user'" class="cu-avatar round" :style="'background-image:url(' + otherData.otherImg + ')'" @click="toUrl(1, chat, otherData)"></view>

							<!-- 消息详情 -->
							<view class="main">
								<!-- 名片 -->
								<view class="card-box" v-if="chat.isCard">
									<uni-card @click="toUrl(1, chat, otherData)" acWidth="500rpx" style="padding: 0;">
										<view class="u-flex">
											<image style="width: 100rpx;height: 100rpx;border-radius: 50%;margin-right: 20rpx;" :src="chat.msg && chat.msg.usrImg" mode=""></image>
											<view class="u-flex u-flex-col u-col-top">
												<text style="font-size: 30rpx;font-weight: bold;color: #000000;">{{chat.msg && chat.msg.usrName}}</text>
												<text>{{chat.msg && chat.msg.note}}</text>
											</view>
										</view>
									</uni-card>
								</view>
								<!-- 消息 -->
								<view class="content" style="max-width: 480rpx;" :class="chat && chat.identify !== 'user' ? 'bg-white' : 'bg-gradual-purple'" v-else>
									<u-parse v-if="chat && chat.identify == 'customer_service'" :html="String(chat && chat.msg)"></u-parse>
									<image style="max-width:200rpx;max-height: 200rpx;" class="chat-img" v-if="chat && chat.identify == 'user' && chat.type == 1" :src="String(chat && chat.imgs)" @click="preview(chat)" @longtap="copyDelete(1,chat,index)"></image>
									<u-tooltip v-if="chat && (chat.identify == 'user' && chat.type == 0)" class="cus_tooltip" @click="clickIdx=>copyDelete(clickIdx,chat,index)" :text="chat && chat.msg" :buttons="['删除']" :color="chat && chat.identify !== 'user' ? '#606266' : '#ffffff'"></u-tooltip>
								</view>
							</view>

							<!-- 自己的头像 -->
							<view v-if="chat && chat.identify === 'user'" class="cu-avatar round" :style="'background-image:url(' + useData.useImg + ')'" @click="toUrl(1, chat, otherData)"></view>
						</view>
					</view>
				</block>
			</view>

			<view class="scroll-bottom" style="height: 160rpx;" id="scrollBottom"></view>

		</scroll-view>
		<!-- 底部功能栏，输入栏 -->
		<view class="cu-bar foot input u-flex-col">
			<!-- 输入栏 -->
			<view class="cu-bar u-flex-1" style="width: 100%;">
				<view class="input-wrap" style="margin: 0 20rpx;display: flex;align-items: center;" @click="focuInp">
					<!-- <view class="input-box"> -->
					<input class="input" placeholder-style="font-size:24rpx;color:#999;" :placeholder="showInput==true?'点击关闭':'点击输入'" type="text" confirm-type="发送" :focus="false" cursor-spacing="30" disabled="true" style="pointer-events: none" />
				</view>
				<!-- <button v-if="isFocus" class="u-reset-button send-btn shadow" @tap.stop="onSend">发送</button> -->
				<button class="u-reset-button more-btn" @tap.stop="onTools">
					<u-icon name="plus-circle" size="25"></u-icon>
				</button>
			</view>

			<!-- 输入内容栏 -->
			<view class="comment-submit-box" v-if="showInput" :style="{bottom: inputBottom+'px'}">
				<view class="comment-add" :style="'bottom:' + KeyboardHeight + 'px'">
					<view class="comment-submit">
						<u-icon name="close-circle" @click="showInput = false" size="22"></u-icon>
						<text class="alway-yu" @tap.stop="onSend">发送</text>
					</view>
					<view class="comment-add" :style="'bottom:' + KeyboardHeight + 'px'">
						<textarea placeholder="请输入发送的内容" class="textarea" v-model="msgText" :maxlength="-1" :auto-height="true" :show-confirm-bar="false" :cursor-spacing="30" :fixed="true" :adjust-position="true" @focus="focusTextarea" @blur="blurTextarea"></textarea>
					</view>
				</view>
			</view>

			<!-- 工具栏 -->
			<view class="tools-box u-flex" style="width: 100%;" v-if="showTools && !showEmoji">
				<u-upload :showProgress="false" :showUploadList="false" :base64="true" @on-uploaded="uploadSuccess" maxCount="1" :customBtn="true" :show-tips="false" class="u-flex-1 tools-item">
					<view class="tools-item u-flex-1" slot="addBtn">
						<image class="item-img" :src="'http://file.shopro.top' + '/imgs/chat/imgs_icon.png'" mode=""></image>
						<text class="item-title">图片</text>
					</view>
				</u-upload>
				<!-- #ifndef MP-WEIXIN -->
				<view class="tools-item u-flex-1" @tap="showEmoji = true">
					<image class="item-img" :src="'http://file.shopro.top' + '/imgs/chat/goods_icon.png'" mode=""></image>
					<text class="item-title">表情</text>
				</view>
				<!-- #endif -->
				<view class="tools-item u-flex-1" @tap="onToolItem(18)">
					<image class="item-img" :src="'http://file.shopro.top' + '/imgs/chat/goods_icon.png'" mode=""></image>
					<text class="item-title">名片</text>
				</view>
				<!-- #ifdef MP-WEIXIN -->
				<view class="tools-item u-flex-1" @tap="showMore">
					<image class="item-img" :src="'http://file.shopro.top' + '/imgs/chat/goods_icon.png'" mode=""></image>
					<text class="item-title">更多</text>
				</view>
				<!-- #endif -->
			</view>

			<!-- 表情栏 -->
			<view class="emoji-box" v-if="showEmoji">
				<u-icon name="close" style="position: absolute;right: 30rpx;top:90rpx;" bold size="20" @click="showEmoji = false;showTools = true"></u-icon>
				<swiper class="emoji-swiper" :indicator-dots="true" circular indicator-active-color="#7063D2" indicator-color="rgba(235, 231, 255, 1)" :autoplay="false" :interval="3000" :duration="1000">
					<swiper-item v-for="(memoji, index) in newEmojiList" :key="index">
						<view class="swiper-item u-flex u-col-center">
							<view class="emoji-img" v-for="(memo, mindex) in memoji" :key="memo.file" @tap="onEmoji(memo)">
								<text style="font-size: 40rpx;">{{memo}}</text>
							</view>
						</view>
					</swiper-item>
				</swiper>
			</view>

			<!-- 商品/订单 -->
			<view class="cu-bar log-box foot input u-flex-col" v-if="showLogBox">
				<view class="log-head u-flex u-row-between" style="width: 100%;">
					<view class="title-box">{{ logTitle }}</view>
					<u-icon name="close-circle-fill" @tap="closeToolsItem" class="uicon-close-circle-fill"></u-icon>
				</view>
				<view class="log-content">
					<scroll-view class="card-scroll-box" scroll-y="true" :scroll-with-animation="true" :show-scrollbar="false" @scrolltolower="loadMore">
						<!-- 商品 -->
						<view class="log-item" v-for="(item, index) in viewList" :key="index" @tap="onViewCard(item)" v-if="cardType === 18">
							<view class="u-flex log-card">
								<view class="img-wrap">
									<image class="goods-img" :src="item.cardMsg && item.cardMsg.usrImg" mode=""></image>
								</view>
								<view class="u-flex-col u-row-between card-right">
									<view class="goods-title u-ellipsis-2">{{item.cardMsg && item.cardMsg.usrName}}
									</view>
									<view class="num-box">{{item.cardMsg && item.cardMsg.note}}</view>
								</view>
							</view>
						</view>
						<u-loadmore height="80rpx" :status="loadStatus" icon-type="flower" color="#ccc" />
					</scroll-view>
				</view>
			</view>
		</view>
		<!-- 遮罩 -->
		<view class="cu-modal" @tap="onMask" :class="{ show: showTools || showEmoji }" style="z-index: 1000;"></view>

	</view>
</template>
<script>
	import Socket from '@/static/js/socket.js';
	import {
		mapMutations,
		mapActions,
		mapState,
		mapGetters
	} from 'vuex';
	import {
		queryFriends,
		deleteMySendMsg
	} from '@/common/api/msg.js';
	import {
		setOnePeo,
		getnowtime,
		getRandomWord,
		duplicateRemoval
	} from '@/utils/common.js'
	import emoji from "./emoji.js";
	import {
		getToken
	} from '@/utils/token.js'
	import {
		pathToBase64
	} from './toBase64.js'
	export default {
		props: ['useNum'],
		data() {
			return {
				socket: null, //socket服务
				InputBottom: 0,
				navTitle: '连接中...', //标题栏
				scrollInto: '', //scrollBottom
				lastId: '', //加载历史聊天记录用
				logmsgList: [], //历史消息
				imgBase: '',
				emojiList: [], //表情包
				newEmojiList: [], //分层后的表情数据
				loadText: {
					loadmore: '点击加载更多',
					loading: '正在加载，请喝杯茶...',
					nomore: '我也是有底线的'
				},
				logStatus: 'loadmore',
				cardType: '', //卡片分类
				currentPage: 1,
				lastPage: 1,
				chatMsgList: [],
				msgText: '', //输入框内容
				showNotice: true, //滚动提示
				showTools: false, //工具栏显示
				showLogBox: false, //商品订单栏
				showEmoji: false, //表情显示

				logTitle: '', //；栏目标题

				otherData: {
					otherNum: '',
					otherImg: ''
				},
				useData: {
					useNum: '',
					useImg: ''
				},
				// 名片,分页。
				loadStatus: 'loadmore', //loadmore-加载前的状态，loading-加载中的状态，nomore-没有更多的状态
				viewList: [],
				viewCurrentPage: 1,
				viewTotalPage: 1,
				submit: false,
				KeyboardHeight: 0,
				showInput: false,
				scrollTop: 1000,
				inputBottom: 0,
				itemAverageHeight: 500, //每条数据平均高度，为确保能滚到底部，可以设置大一些
			};
		},
		computed: {
			...mapGetters(['chatList', 'chatItem']),
			isFocus() {
				//检测输入框是否有信息
				let isMsg = false;
				this.msgText ? (isMsg = true) : (isMsg = false);
				return isMsg;
			},
			isClose() {
				if (this.socket) {
					return this.socket.isClose;
				}
				return null;
			}
		},
		created: function() {
			//创建聊天
			this.init()
		},
		beforeDestroy: function() {
			this.socket.close()
			this.socket = null
		},
		methods: {
			focusTextarea(e) {
				console.log('获取焦点')
				this.inputBottom = e.detail.height;
				this.scrollTop += 1; //滚到底部
			},
			blurTextarea(e) {
				console.log('失去焦点')
				this.inputBottom = 0;
				this.scrollTop += 1; //滚到底部
			},

			delImg: function(e) {
				var that = this,
					imgUrlList = that.data.imgUrlList,
					index = e.currentTarget.dataset.index; //获取当前长按图片下标
				wx.showModal({
					title: '系统提醒',
					content: '确定要删除此图片吗？',
					success: function(res) {
						if (res.confirm) {
							imgUrlList.splice(index, 1);
						} else if (res.cancel) {
							return false;
						}
						that.setData({
							imgUrlList: imgUrlList
						});
					}
				})
			},
			//时间戳的处理    
			formatDate: function(value) {
				var date = new Date(value);
				//date.setTime(value);
				var month = date.getMonth() + 1;
				var hours = date.getHours();
				if (hours < 10)
					hours = "0" + hours;
				var minutes = date.getMinutes();
				if (minutes < 10)
					minutes = "0" + minutes;
				var time = date.getFullYear() + "-" + month + "-" + date.getDate() + " " + hours + ":" + minutes;
				return time;
			},
			closeAll() {
				this.showInput = false
				this.showEmoji = false
				this.showTools = false
			},
			focuInp() {
				console.log('点击了')
				this.showInput = !this.showInput
				if (this.showInput) {
					this.showTools = false
					this.showEmoji = false
				}
			},
			// 没用的方法，但不要删
			stopPrevent() {
				window.event.stopPropagation(); //阻止浏览器默认事件冒泡
			},
			showMore() {
				this.$emit('showMore', true)
			},
			//点击名片发送
			onViewCard(item) {
				//console.log(item,'发送名片')
				item.cardMsg.isCard = true
				this.sendWs(item.cardMsg, 0);
				this.pushChat(item.cardMsg, 0);
				this.showLogBox = false;
			},
			// 加载更多
			loadMore() {
				if (this.cardType === 18) {
					if (this.viewCurrentPage < this.viewTotalPage) {
						this.viewCurrentPage += 1;
						this.queryFriends();
					}
				}
			},
			// 关闭工具栏项
			closeToolsItem() {
				this.showLogBox = false;
			},
			// 工具栏功能项
			onToolItem(type) { //名片工具点击
				this.viewList = [];
				this.viewCurrentPage = 1;
				this.viewTotalPage = 1;
				this.cardType = type;
				let map = new Map(); //键值对
				map.set(18, () => {
					this.logTitle = '我的好友';
					this.showLogBox = true;
					this.showTools = false
					this.queryFriends();
				});
				map.set('imgs', this.chooseImg);

				map.get(type)();
			},
			// 名片记录
			queryFriends() {
				this.loadStatus = 'loading'
				queryFriends({
					userId: getToken('useNum'),
					friendTypeId: getToken('version') == 1 ? 0 : 1,
					status: 1,
					'page.current': this.viewCurrentPage,
					friendsType: 0,
					lat: 1,
					lng: 1
				}).then(res => {
					if (res.data) {
						let data = res.data && res.data.rows
						data = data.filter(v => {
							return v.usrCraftsman && v.usrCraftsman.usrName || v.usrCompany && v.usrCompany.companyNameCn
						})
						data && data.forEach(m => {
							m.cardMsg = {
								craftsmanModuleNo: m.friendTypeId == 0 ? (m.usrCraftsman && m.usrCraftsman.moduleNo) : (m.usrCompany && m.usrCompany.moduleNo),
								usrNo: m.firendId,
								usrName: m.friendTypeId == 0 ? (m.usrCraftsman && m.usrCraftsman.usrName) : (m.usrCompany && m.usrCompany.companyNameCn),
								usrImg: m.friendTypeId == 0 ?
									'https://www.ydylmold.cn/images/ydylapp/usrCraftsman/image/' + (m.usrCraftsman && m.usrCraftsman.headImg) : 'https://www.ydylmold.cn/images/ydylapp/usrCompany/image/' + (m.usrCompany && m.usrCompany.companyLogo),
								note: m.friendTypeId == 0 ? '个人名片' : '企业名片',
								usrType: m.friendTypeId
							}
						})
						this.viewList = duplicateRemoval(this.viewList, data, 'id')
						this.viewTotalPage = res.data.total;
						this.loadStatus = this.viewCurrentPage < res.data.total ? 'loadmore' : 'nomore';
					}
				})
			},
			toUrl(type, item, otherData) {
				// console.log(item,888)
				// console.log(otherData,999)
				if (type == 1) { //跳转名片
					this.$store.commit('toUserIndex', {
						moduleNo: (item.msg && item.msg.craftsmanModuleNo) || item.moduleNo,
						craftsmanId: item.identify == 'customer_service' ? otherData.otherNum : '',
						companyId: item.identify == 'customer_service' ? otherData.otherNum : ''
					})
				}
			},
			// 长按复制和删除
			copyDelete(copyindex, item, index) {
				console.log('copyindex', copyindex, item, index)
				if (copyindex == 1) {
					if (item.type == 1) {
						uni.showModal({
							title: '删除图片',
							content: '确定删除图片?',
							success: res => {
								if (res.confirm) {
									// 删除图片 将数据置空
									deleteMySendMsg({
										id: item.id, // 聊天编号
										// 发送者编号
										sendUserNo: getToken('useNum')
									}).then(res => {
										this.chatMsgList.splice(index, 1); //从第index个元素，删除1个
										this.$u.toast('删除成功！')
									})
								} else if (res.cancel) {
									console.log('用户点击取消');
								}
							}
						})
					} else {
						deleteMySendMsg({
							id: item.id, // 聊天编号
							// 发送者编号
							sendUserNo: getToken('useNum')
						}).then(res => {
							this.chatMsgList.splice(index, 1); //从第index个元素，删除1个
							this.$u.toast('删除成功！')
						})
					}
				}
			},
			// 点击图片进行预览
			preview(item) {
				console.log('预览', item)
				var imgArr = []
				// 新建一个存放预览图片的空数组
				imgArr.push(item.imgs);
				uni.previewImage({
					current: 0,
					urls: imgArr,
					// longPressActions: {
					// 	itemList: ['发送给朋友', '保存图片', '收藏'],
					// 	success: function(data) {
					// 		console.log('选中了第' + (data.tapIndex + 1) + '个按钮,第' + (data.index + 1) + '张图片');
					// 	},
					// 	fail: function(err) {
					// 		console.log(err.errMsg);
					// 	}
					// }
				})
			},
			// 滚动到顶部 查看更多
			logLoadmore() {
				if (this.currentPage == 0) {
					this.chatMsgList = []
				}
				if (this.currentPage < this.lastPage) {
					this.currentPage += 1;
					this.chatLog();
				} else {
					this.logStatus = 'nomore';
				}
			},
			init() {
				this.socket = new Socket({
						ping: 10000,
						lockReconnect: true
					},
					msg => {
						this.parseMsgStatus(msg.data); //监听消息
					}
				);
				this.emojiList = emoji.slice(0, 100) //截取100个表情
				this.newEmojiList = this.sortData(this.emojiList, 30); //每30个一组
			},

			// 数据分层
			sortData(oArr, length) {
				let arr = [];
				let minArr = [];
				oArr.forEach(c => {
					if (minArr.length === length) {
						minArr = [];
					}
					if (minArr.length === 0) {
						arr.push(minArr);
					}
					minArr.push(c);
				});
				return arr;
			},

			// 时间显示
			showTime(timestamp, index) {
				timestamp = parseInt(timestamp);
				// 判断用户输入的时间戳是秒还是毫秒,一般前端js获取的时间戳是毫秒(13位),后端传过来的为秒(10位)
				if (timestamp.toString().length == 10) timestamp *= 1000;
				// console.log('timestamp', timestamp);
				let timer = new Date().getTime() - timestamp;
				timer = parseInt(timer / 1000);
				// console.log('timer', timer);
				if (timer >= 300) {
					return true;
				}
			},

			jump(path, parmas) {
				this.$Router.push({
					path: path,
					query: parmas
				});
			},
			setInitData(obj, isLa = true) {
				this.$store.commit('setChatItem', obj)
				uni.setNavigationBarTitle({
					title: obj && obj.nickname || ''
				})
				//初始化聊天参数
				if (getToken('version') == 1) {
					//当前是个人
					this.useData.useImg = this.$filePath + this.$useLogo + (getToken('userInfo') && getToken('userInfo')
						.headImg)
					this.otherData.otherImg = this.$filePath + this.$useLogo + this.chatItem.shopLogo
					this.useData.nickname = getToken('login').usrName
					this.otherData.nickname = this.chatItem.nickname

				} else {
					this.useData.useImg = this.$filePath + this.$compLogo + (getToken('complogin') && getToken('complogin').companyLogo)
					this.otherData.otherImg = this.$filePath + this.$compLogo + this.chatItem.shopLogo
					this.useData.nickname = this.chatItem.nickname
					this.otherData.nickname = getToken('login').usrName
				}
				//设置头像数据
				if (String(this.chatItem.createNo) == getToken('useNum')) {
					this.otherData.otherNum = this.chatItem.objectNo
					this.useData.useNum = this.chatItem.createNo
				} else {
					this.otherData.otherNum = this.chatItem.createNo
					this.useData.useNum = this.chatItem.objectNo
				}

				if (this.chatItem.messageNum && isLa) { //拉取未读消息
					let msgUnRead = {
						action: 8,
						chatMsg: {
							selfNo: this.useData.useNum,
							chatNo: this.chatItem.chatNo
						},
						extand: null
					}
					this.socket.send(JSON.stringify(msgUnRead))
				} else { //拉取聊天记录
					this.chatLog()
					this.goBottom()
				}
			},
			//发送已读
			sendRead(arr) {
				let msgIsRead = {
					action: 3,
					chatMsg: {},
					extand: arr.join(',')
				}
				this.socket.send(JSON.stringify(msgIsRead))
			},
			initMsgList(msgList, action) {
				let arrCurr = []
				let acCurr = []
				if (msgList && msgList.length) {
					msgList.forEach(item => {
						let msgCurr = this.parseMsg(item, item.sendUserNo == getToken('useNum') ? 'user' : 'customer_service')
						if (msgCurr) {
							arrCurr.push(msgCurr)
						}
						if (action == 8) {
							acCurr.push(item.id)
						}
					});
					this.logmsgList = arrCurr.concat(this.chatMsgList);
					this.chatMsgList = this.logmsgList;
					console.log('this.chatMsgList', this.chatMsgList);
				}

				if (action == 8) { //发送已读
					this.currentPage = 0
					if (acCurr && acCurr.length) {
						this.sendRead(acCurr)
						this.currentPage = Math.floor(this.chatMsgList.length / 10)
						//改变聊天列表
						let chatArr = this.chatList
						let idx = chatArr.findIndex(v => {
							return v.chatNo == this.chatItem.chatNo
						})
						if (idx != -1) {
							chatArr[idx].messageNum = 0
							let item = chatArr[idx]
							chatArr.splice(idx, 1, item)
						}
						this.$store.commit('setChatList', chatArr)
					}
					this.goBottom()
				}

			},

			// 解析链接状态
			parseMsgStatus(msgStr) {
				let obj = JSON.parse(msgStr);
				if (obj.action == 2) {
					let acMsg = obj.data && obj.data.chatMsg
					if (acMsg && acMsg.chatNo == this.chatItem.chatNo) {
						this.chatMsgList.push({
							identify: 'customer_service',
							type: Number(acMsg.msgType),
							msg: JSON.parse(acMsg.content).content,
							date: acMsg.sendTime
						});
						this.sendRead([acMsg.msgId]);
					}
					this.goBottom();
				}
				if (obj.chatMsg) {
					obj.chatMsg.lastContent = obj.chatMsg.content
					let msgCurr = this.parseMsg(obj.chatMsg, obj.chatMsg.sendUserNo == getToken('useNum') ? 'user' : 'customer_service')
					if (obj.action != 5 && obj.action != 6) {
						this.chatMsgList.push(msgCurr)
					}
					this.sendRead([msgCurr.id])
					this.goBottom();
				}
				if (obj.action == 1 && obj.data.code == 200) {
					this.navTitle = '连接成功';
					if (this.chatItem.chatNo) {
						this.setInitData(this.chatItem, true)
						return
					}
					//判断这条记录创建与否
					let checkmsg = {
						action: 5,
						chatMsg: {
							selfNo: getToken('useNum'),
							friendNo: this.useNum,
							entity: "usrChatObjectItem"
						},
						extand: null
					}
					this.socket.send(JSON.stringify(checkmsg));
				}
				if (obj.action == 5) {
					let listData = obj.data && obj.data.listData
					if (listData && listData.length == 0) {
						//创建联系人
						let onedata = setOnePeo(this.useNum);
						this.socket.send(JSON.stringify(onedata))
					} else {
						this.setInitData(obj.data.listData[0]);
					}
				}
				if (obj.action == 6) { //新建记录
					if (obj.data && obj.data.code == 1) {
						this.setInitData(obj.data && obj.data.data, false);
					} else {
						this.$u.toast('连接失败，请刷新后重试');
					}
				}
				if (obj.action == 8) { //未读消息
					if (obj.data && obj.data.length) { //拿到未读消息
						let msgList = obj.data;
						this.lastId = msgList[0] && msgList[0].id; //?
						this.initMsgList(msgList, obj.action);
					}
				}
				if (obj.action == 9) { //历史记录
					if (obj.data && obj.data.code == 1) { //拿到聊天记录
						let msgList = obj.data.listData;
						this.lastId = msgList[0] && msgList[0].id; //?
						this.lastPage = obj.data.size;
						let arrCurr = []
						this.initMsgList(msgList, obj.action)
					}
					if (this.currentPage == this.lastPage) {
						this.logStatus = 'nomore';
					}
				}

			},

			// 解析消息类型,接受数据时才用，发送数据时不用。 message:每一条消息 identify：用户发送的为 user;客服发送的为customer_service
			parseMsg(message, identify) {
				//console.log('解析消息类型', message, identify);
				let obj = null;
				switch (Number(message.msgType)) {
					case 'system':
						obj = {
							identify: 'customer_service', // 用户发送的为 user; 客服发送的为 customer_service
							type: 'system', //message:用户消息类型; message_list:请求消息列表 系统
							msg: message.message,
							id: message.id || message.msgId,
							moduleNo: getToken('version') == 1 ? (message.usrCraftsman && message.usrCraftsman.moduleNo || 'ydylapp2003') : (message.usrCompany && message.usrCompany.moduleNo || 'ydylapp1003')
						};
						break;
					case 1:
						obj = {
							identify: identify, // 用户发送的为 user; 客服发送的为 customer_service
							type: Number(message.msgType), //message:用户消息类型; message_list:请求消息列表
							msg: `<img class="chat-img" src="${JSON.parse(message.content) && JSON.parse(message.content).img}"/>`,
							imgs: JSON.parse(message.content) && JSON.parse(message.content).img,
							server_avatar: this.useData.useImg,
							date: message.sendTime,
							id: message.id || message.msgId,
							moduleNo: getToken('version') == 1 ? (message.usrCraftsman && message.usrCraftsman.moduleNo || 'ydylapp2003') : (message.usrCompany && message.usrCompany.moduleNo || 'ydylapp1003')
						};
						break;
					case 0:
						obj = {
							identify: identify, // 用户发送的为 user; 客服发送的为 customer_service
							type: Number(message.msgType), //message:用户消息类型; message_list:请求消息列表
							msg: (JSON.parse(message.content) && JSON.parse(message.content).content) || JSON.parse(message.content),
							server_avatar: this.useData.useImg,
							isCard: JSON.parse(message.content) && JSON.parse(message.content).content ? false : true,
							date: message.sendTime,
							id: message.id || message.msgId,
							moduleNo: getToken('version') == 1 ? (message.usrCraftsman && message.usrCraftsman.moduleNo || 'ydylapp2003') : (message.usrCompany && message.usrCompany.moduleNo || 'ydylapp1003')
						};
						break;
					default:
						break;
				}
				return obj;
			},

			// 获取历史聊天记录
			async chatLog() {

				let hisMsg = {
					action: 9,
					chatMsg: {
						selfNo: getToken('useNum'),
						page: this.currentPage,
						chatNo: this.chatItem.chatNo
					},
					"extand": null
				}
				this.socket.send(JSON.stringify(hisMsg))
			},

			// 获取焦点
			InputFocus(e) {
				this.onMask();
			},
			// 失去焦点
			InputBlur(e) {
				this.InputBottom = 0;
			},
			// 输入
			onInput(e) {},



			// 点击工具栏开关
			onTools() {
				this.showInput = false
				if (this.isClose) {
					this.$u.toast('您已掉线！请返回重试');
					return;
				}
				this.showEmoji = false;
				this.showTools = !this.showTools;
			},

			// 选择表情
			selEmoji() {
				this.showTools = false;
				this.showLogBox = false;
				this.showEmoji = !this.showEmoji;
			},
			// 点击表情
			onEmoji(item) {
				this.msgText += item;
			},

			// 点击遮罩
			onMask() {
				this.showTools = false;
				this.showLogBox = false;
				this.showEmoji = false;
			},

			//关闭滚动提示
			closeNotice() {
				this.showNotice = false;
			},

			// 滚动底部
			goBottom() {
				let timeout = null;
				this.scrollInto = '';
				clearTimeout(timeout);
				timeout = setTimeout(() => {
					this.scrollInto = 'scrollBottom';
				}, 300);
			},

			// 发送图片
			uploadSuccess(list) {
				pathToBase64(list.tempFilePaths[0])
					.then(base64 => {
						this.sendWs({
							imgData: base64
						}, 1);
						this.pushChat(`<img class="chat-img" src="${base64}"/>`, 1, base64);
						// this.imgBase = base64;
						this.showTools = false;
					})
					.catch(error => {})
				console.log('this.imgBase', this.imgBase)
			},

			// 发送问题
			async onQuestion(question) {
				this.pushChat(question.content, 0, 'customer_service');

			},
			// 发送消息
			onSend() {
				// this.msgText 发送的内容
				if (this.msgText) {
					this.sendWs({ //发送信息
						content: this.msgText
					}, 0);
					this.pushChat(this.msgText, 0); //发送本地数据
					this.msgText = '';
					this.showInput = false
				}

				this.showEmoji && this.onMask();
				this.scrollTop = this.scrollTop + this.itemAverageHeight; //滚到底部
			},

			// 发送服务数据
			async sendWs(data, type = 0) {
				let msg = {
					action: 2, // 用户发送的为 user; 客服发送的为 customer_service
					chatMsg: {
						selfNo: this.useData.useNum,
						friendNo: this.otherData.otherNum,
						chatNo: this.chatItem.chatNo,
						msgType: type,
						msgId: '',
						content: type != 1 ? data : '',
						entity: 'usrChatObjectItem'
					}, //message:用户消息类型; message_list:请求消息列表
					"extand": null
				};
				//设置图片
				if (type == 1) {
					msg.chatMsg.imgData = data
				}
				// 设置消息id
				let time = getnowtime('YYYYMMDDhhmmss')
				let str = getRandomWord(false, 5)
				msg.chatMsg.msgId = time + str
				let strMsg = JSON.stringify(msg);

				let res = await this.socket.send(strMsg);
				this.showInput = false
			},

			// 发送本地数据。
			pushChat(data, type = 0, data1) {
				if (this.isClose) {
					this.$u.toast('您已掉线！请返回重试');
					return;
				}
				this.chatMsgList.push({
					identify: 'user',
					type: type,
					msg: data,
					imgs: data1,
					date: new Date().getTime(),
					isCard: data.isCard ? true : false
				});
				this.imgBase = null;
				console.log('this.chatMsgList', this.chatMsgList);
				this.goBottom();
			},

			// 表情地址
			selEmojiFile(name) {
				for (let index in this.emojiList) {
					if (this.emojiList[index].name === name) {
						return this.emojiList[index].file;
					}
				}
				return false;
			},

		}
	};
</script>

<style lang="scss">
	@import './chat.scss';

	.cus_tooltip {
		width: 100%;
		display: inline-block;
		white-space: pre-wrap;
		word-wrap: break-word;
		height: auto;
	}

	// #ifdef H5
	.cu-chat .cu-item>.main .content .u-tooltip>:first-child {
		white-space: pre-wrap;
	}

	// #endif

	// #ifdef MP-WEIXIN
	.cu-chat .cu-item>.main .content .u-tooltip:first-child {
		white-space: pre-wrap;
		flex-shrink: -1;
	}

	img {
		max-width: 280rpx;
		height: auto;
	}

	// #endif
	.disabled {
		pointer-events: none;
	}

	.input-wrap {
		padding: 0 20rpx;
		background: #f2f2f2;
		border-radius: 32rpx;
		flex: 1;
		min-height: 60rpx;
		line-height: 60rpx;

		.input {
			width: 100%;
		}
	}

	// 重置样式
	page {
		overflow: hidden;
	}

	.cu-avatar {
		border: 1rpx solid #eeeeee;
	}

	// 标题栏
	.head-box {
		.head-title {
			font-size: 38rpx;
			line-height: 38rpx;
			white-space: pre-wrap;
		}

		.head-icon {
			font-size: 34rpx;
			line-height: 38rpx;
		}

		.text-green {
			color: #18b566;
		}

		.text-gray {
			color: #fa3534;
		}

		.head-state {
			font-size: 28rpx;
			line-height: 38rpx;
		}
	}

	// 聊天框
	.chat-wrap {
		height: 100vh;
		overflow: hidden;
		background-color: #F8F6FC;

		.scroll-box {
			height: 100%;
		}

		.cu-chat {
			.time-box {
				display: flex;
				align-items: center;
				justify-content: left;

				.cu-info {
					border-radius: 26rpx;
					background: rgba(#000, 0.1);
					padding: 6rpx 20rpx;
				}
			}

			.main {
				margin: 0 20rpx;
				max-width: calc(100% - 80px);
			}

			.cu-item>.main .content {
				&::after {
					width: 0;
					height: 0;
				}

				&::before {
					width: 0;
					height: 0;
				}
			}
		}
	}

	// 底部
	.foot {
		padding: 0 20rpx;

		.input-wrap {
			background: #f2f2f2;
			border-radius: 32rpx;
			flex: 1;
			height: 60rpx;

			.input {
				width: 100%;
			}
		}

		.send-btn {
			padding: 0;
			width: 110rpx;
			line-height: 64rpx;
			background: linear-gradient(90deg, #a36fff, #5336ff);
			border-radius: 32rpx;
			color: #fff;
		}

		.more-btn {
			padding: 0;
			background: none;

			.icon-icon_tianjia {
				font-size: 44rpx;
				background: linear-gradient(90deg, #a36fff, #5336ff);
				-webkit-background-clip: text;
				color: transparent;
				transition: all linear 0.2s;
			}

			.tools-active {
				transform: rotate(45deg);
				transition: all linear 0.2s;
			}
		}
	}

	// 工具栏
	.tools-box {
		background-color: #fff;
		height: 310rpx;
		border-top: 1rpx solid #f6f6f6;
		transition: all 0.3s ease-in-out 0s;

		.tools-item {
			align-items: center;
			justify-content: center;
			display: flex;
			flex-direction: column;

			.item-img {
				width: 70rpx;
				height: 70rpx;
				margin-bottom: 30rpx;
			}

			.item-tile {
				font-size: 24rpx;
				font-weight: 500;
				color: #333333;
			}
		}
	}

	// 商品卡片
	.goods-card {
		width: 100%;

		.goods-img {
			width: 116rpx;
			height: 116rpx;
			margin-right: 20rpx;
		}

		.card-right {
			width: 330rpx;
			height: 116rpx;

			.goods-title {
				width: 330rpx;
				font-size: 26rpx;
				font-weight: 500;
				color: #333333;
				line-height: 32rpx;
				text-align: left;
			}

			.price-box {
				width: 100%;

				.goods-price {
					font-size: 26rpx;
					font-weight: 500;
					color: #ff3000;

					&::before {
						content: '￥';
						font-size: 20rpx;
					}
				}

				.goods-state {
					font-size: 24rpx;
					font-weight: 500;
					color: #603fff;
				}
			}
		}
	}

	// 订单卡片样式
	.order-chat {
		width: 100%;

		.order-code {
			font-size: 24rpx;
			width: 100%;
			font-weight: 400;
			color: #999999;
			border-bottom: 1rpx solid rgba(#dfdfdf, 0.5);
			padding: 0 0rpx 10rpx;
		}
	}

	// 订单商品记录
	.log-box {
		width: 750rpx;
		height: 600rpx;
		background: #f2f2f2;
		border-radius: 20rpx 20rpx 0px 0px;
		display: flex;
		flex-direction: column;

		.log-head {
			box-sizing: border-box;
			width: 750rpx;
			height: 94rpx;
			background: #ffffff;
			border-radius: 20rpx 20rpx 0px 0px;
			padding: 0 26rpx;

			.title-box {
				font-size: 30rpx;
				font-weight: 500;
				color: #333333;
				line-height: 90rpx;
				border-bottom: 4rpx solid #7063d2;
			}

			.close-btn {
				padding: 0;
				background: none;
			}
		}

		.log-content {
			flex: 1;
			height: 100%;
			width: 100%;
			overflow: hidden;
			background: #f2f2f2;

			.card-scroll-box {
				height: 100%;
				width: 100%;
				background: #f2f2f2;
			}

			.log-item {
				width: 690rpx;
				margin: 20rpx;
				background-color: #fff;
				border-radius: 20rpx;

				.code-box {
					border-bottom: 1rpx solid rgba(#dfdfdf, 0.5);
					height: 76rpx;
					padding: 0 20rpx;

					.code-text,
					.date-text {
						font-size: 24rpx;
						font-weight: 400;
						color: #999999;
					}
				}

				.log-card {
					padding: 30rpx 20rpx;
				}

				.goods-img {
					width: 140rpx;
					height: 140rpx;
					margin-right: 20rpx;
				}

				.card-right {
					width: 500rpx;
					height: 140rpx;

					.goods-title {
						font-size: 26rpx;
						font-weight: 500;
						color: #333333;
						line-height: 32rpx;
						text-align: left;
						width: 500rpx;
					}

					.num-box {
						font-size: 24rpx;
						font-weight: 400;
						color: #999999;
						text-align: left;
						width: 100%;
					}

					.price-box {
						width: 100%;

						.goods-price {
							font-size: 26rpx;
							font-weight: 500;
							color: #333333;

							&::before {
								content: '￥';
								font-size: 20rpx;
							}
						}

						.goods-state {
							font-size: 24rpx;
							font-weight: 500;
							color: #603fff;
						}
					}
				}
			}
		}
	}

	// 表情栏
	.emoji-box {
		width: 100%;
		background-color: #fff;
		height: 310rpx;
		border-top: 1rpx solid #f6f6f6;
		transition: all 0.3s ease-in-out 0s;
		padding: 30rpx 0 20rpx 0;

		.emoji-swiper {
			height: 280rpx;

			.swiper-item {
				flex-wrap: wrap;
			}
		}

		.emoji-img {
			width: 50rpx;
			height: 50rpx;
			display: inline-block;
			margin: 10rpx;
		}
	}

	//输入框
	.comment-submit-box {
		display: flex;
		align-items: flex-end;
		width: 100%;

		.comment-add {
			background-color: #FFFFFF;
			width: 98%;
			padding: 5rpx;
			border: 1px solid #ddd;
			transition: .3s;
			-webkit-transition: .3s;
		}

		.btn-click {
			background-color: #007AFF;
			font-size: 28rpx;
			padding: 10rpx 20rpx;
			color: #FFFFFF;
			border-radius: 30rpx;
		}

		.cancel {
			color: #606266;
		}

		.textarea {
			height: 100px;
			padding: 16rpx;
			width: 620rpx;
		}

		.comment-submit {
			padding: 5rpx 20rpx 10rpx 20rpx;
			border-bottom: 1px dashed #ddd;
			width: calc(100% - 40rpx);
			display: flex;
			justify-content: space-between;
			align-items: center;
		}

		.alway-yu {
			min-width: 120rpx;
			background: #0080FF;
			border-radius: 10rpx;
			display: flex;
			font-size: 28rpx;
			font-family: Source Han Sans SC;
			font-weight: 500;
			color: #FFFFFF;
			// line-height: 60rpx;
			padding: 10rpx;
			display: flex;
			justify-content: center;
		}
	}
</style>